var _util = require('util/util.js')
require('./index.css')
require('page/common/header/index.js');

var _account_service = require('service/account-service');

var userLogin = {
    init : function(){
        $('#loginMsg').hide();
        this.bindEvents();
        return this;
    },
    bindEvents : function(){
        var _this = this;
        $('#submit').click(
            function(){
                _this.submit();
            }
        );

    },
    submit:function(){
        var formData = {
            username : $.trim($('#username').val()),
            password : $.trim($('#password').val())

        };
        var validationResult = this.formValidation(formData);
        if(validationResult.status){
            // 向服务器发送登录请求,调用service层的js
            _account_service.login(
                formData,
                function(res){
                    window.location.href = _util.getURLParam('redirect')||'./catalog-main.html';
                    // _util.getURLParam('redirect');
                },
                function(errMsg){
                    $('#loginMsg').show().text(errMsg);
                }
                )
        }else{
            $('#loginMsg').show().text(validationResult.msg);
        }
    },
    formValidation : function(formData){
        var result = {
            status : false,
            msg    : ''
        };
        if(!_util.validateField('require',formData.username)){
            result.msg = '用户名不能为空'
            return result;
        }
        if(!_util.validateField('require',formData.password)){
            result.msg = '密码不能为空'
            return result;
        }
        result.status = true;
        result.msg    = '校验通过';
        return result;
    }

};

module.exports = userLogin.init();